package com.snailct.bpp.service.core.reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;

/**
 * Created by huangxa on 2016/7/14.
 */
public class XmlDefinitionReader {
    private static final Log logger = LogFactory.getLog(XmlDefinitionReader.class);
    public Document loadResource(String xml) throws Exception{
        DocumentBuilderFactory factory = createDocumentBuilderFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
        }
        DocumentBuilder builder = createDocumentBuilder(factory);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
        return builder.parse(inputStream);
    }

    protected DocumentBuilderFactory createDocumentBuilderFactory(){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        return factory;
    }
    protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory) throws ParserConfigurationException {
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        return docBuilder;
    }
}
